<template>
  <!-- 小说阅读页面 -->
  <div class="page" @click="pageClick" @touchmove="showMenu = false" ref="page">
    <k-scroll
      class="read-scroll"
      ref="scroll"
      @scroll="scroll"
      topColor="var(--theme)"
      bottomColor="var(--theme)"
      topType="stretch"
      bottomType="stretch"
    >
      <div class="content">
        <!-- 护眼模式 -->
        <div class="view-mask" v-if="careEye"></div>
        <!-- 目录弹窗 -->
        <k-popup
          v-model="popShow"
          :popWidth="catalogue.popWidth"
          :popHeight="catalogue.popHeight"
          :popHiddenX="catalogue.popHiddenX"
          :popHiddenY="catalogue.popHiddenY"
          :popShowX="catalogue.popShowX"
          :popShowY="catalogue.popShowY"
          :rotate="catalogue.rotate"
          :useScale="catalogue.useScale"
          :useOpacity="catalogue.useOpacity"
          :outside="catalogue.outside"
        >
          <!-- 弹窗内容 -->
          <div class="popupStyle">
            <div class="info">
              <img :src="novel.img" />
              <div class="box1">
                <span class="name">{{ novel.name }}</span>
                <span class="author">{{ novel.author }}</span>
              </div>
              <div class="box2">
                <span class="progress">{{ ((chapterIndex / (catalog.length - 1)) * 100).toFixed(2) }}%</span>
                <span class="a">已读</span>
              </div>
            </div>
            <div class="status">
              <span class="c">{{ novel.status }} 共{{ catalog.length - 1 }}章</span>
              <span class="sort" @click="changeSort">{{ sort }}</span>
            </div>
            <div class="scroll2" id="scroll2">
              <div class="list" id="list">
                <div
                  id="titleItem"
                  :class="{
                    item: true,
                    selected: (index == chapterIndex && sort == '倒序') || (index == catalog.length - chapterIndex - 1 && sort == '正序'),
                  }"
                  v-for="(item, index) in catalog"
                  :key="JSON.stringify(item) + index"
                  @click="changeChapter(index)"
                >
                  {{ item.title.replace(/章/, '章 ') }}
                </div>
              </div>
            </div>
          </div>
        </k-popup>
        <!-- 顶部章节指示和奖励计时 -->
        <div class="top" :style="{ transform: chapterIndex ? 'translateY(0rem)' : 'translateY(-0.4rem)' }" @click.stop>
          <span class="nowChapter" v-if="chapterContext.title">{{ chapterContext.title.replace(/章/, '章 ') }}</span>
          <div class="encourage">
            <div class="progress" :style="{ width: readSeconds / 3 + '%' }"></div>
            <span class="num">5金币</span>
          </div>
        </div>
        <!-- 底部状态和广告位 -->
        <div class="bottom" :style="{ transform: chapterIndex ? 'translateY(0rem)' : 'translateY(0.8rem)' }" @click.stop>
          <div class="status">
            <span class="pro">{{ ((chapterIndex / (catalog.length - 1)) * 100).toFixed(2) }}%</span>
            <div class="t">点击屏幕可以唤出菜单</div>
            <div class="te">
              <span class="time">{{ timeStamp | format_nowtime }}</span>
              <div class="ele">
                <img src="@/assets/img/icons/black/battery.svg" />
                <div class="num" :style="{ width: electri * 0.18 + 'rem' }"></div>
              </div>
            </div>
          </div>
          <div class="ad">小广告位</div>
        </div>
        <!-- 顶部操作菜单选项 -->
        <div class="top-menu" :style="{ transform: showMenu ? 'translateY(0rem)' : 'translateY(-0.45rem)' }" @click.stop>
          <img class="back" :src="backIcon" @click.stop="$router.back()" />
          <div class="right">
            <span class="yuan" @click="selectOrigin">换源</span>
            <span class="rack" @click="joinRack">加入书架</span>
            <img class="download" :src="downloadIcon" @click="downLoad" />
            <img class="more" :src="moreIcon" @click="moreClick" />
          </div>
        </div>
        <!-- 自动阅读设置 -->
        <div
          v-if="readAuto"
          class="autoSet"
          @click.stop="showAutoSet = !showAutoSet"
          :style="{
            color: $store.state.theme == 'dark' ? '#8a8a8a' : 'rgb(220,220,220)',
            backgroundColor: $store.state.theme == 'dark' ? 'rgba(28,28,28,0.9)' : 'rgba(88,88,88,0.9)',
          }"
        >
          <span>自动阅读·设置</span>
          <img :src="upIcon" />
        </div>
        <!-- 自动阅读设置内容 -->
        <div
          class="autoSetCon"
          :style="{
            transform: showAutoSet ? 'translateY(0rem)' : 'translateY(2.03rem)',
            color: $store.state.theme == 'dark' ? '#8a8a8a' : 'rgb(220,220,220)',
            backgroundColor: $store.state.theme == 'dark' ? 'rgb(28,28,28)' : 'rgb(88,88,88)',
          }"
          @click.stop
        >
          <div class="slider">
            <van-slider v-model="readSpeed" :min="5" :max="35" bar-height="0.1rem" />
          </div>
          <div class="mark">
            <span>慢速</span>
            <span>标准</span>
            <span>快速</span>
          </div>
          <div class="exit" @click="readAuto = !readAuto">退出自动阅读</div>
        </div>
        <!-- 滑块移动提示 -->
        <div
          class="sliderTip"
          :style="{
            color: $store.state.theme == 'dark' ? '#8a8a8a' : 'rgb(220,220,220)',
            backgroundColor: $store.state.theme == 'dark' ? '#333333' : '#715E40',
            opacity: showChapterTip ? 1 : 0,
          }"
        >
          <div class="progress">{{ ((slider / (catalog.length - 1)) * 100).toFixed(1) }}%</div>
          <div class="chapterTitle" v-if="catalog[slider]">{{ catalog[slider].title.replace(/章/, '章 ') }}</div>
        </div>
        <!-- 底部操作菜单选项 -->
        <div class="bottom-menu" :style="{ transform: showMenu ? 'translateY(0rem)' : 'translateY(1.2rem)' }" @click.stop>
          <!-- 修改章节数 -->
          <div class="chapter-change">
            <span :class="{ able: !chapterIndex }" @click="before">上一章</span>
            <!-- <k-slider></k-slider> -->
            <div class="slider">
              <van-slider
                @drag-start="showChapterTip = true"
                @drag-end="showChapterTip = false"
                v-if="catalog.length"
                v-model="slider"
                @change="sliderChange"
                :min="0"
                :max="catalog.length - 1"
              />
            </div>
            <span :class="{ able: chapterIndex == catalog.length - 1 }" @click="next">下一章</span>
          </div>
          <!-- 亮度调整 -->
          <div class="bright" :style="{ transform: showBright ? 'translateY(-1.6rem)' : 'translateY(0rem)' }">
            <div class="bri">
              <span>亮度</span>
              <div class="slider">
                <van-slider v-model="brightness" :min="0" :max="100" />
              </div>
              <img :src="brightIcon2" />
            </div>
            <div class="eye">
              <span>护眼模式</span>
              <van-switch v-model="careEye" size="0.2rem" />
            </div>
            <div class="line"></div>
          </div>
          <!-- 设置内容 -->
          <div class="setting" :style="{ transform: showSetting ? 'translateY(-2.7rem)' : 'translateY(0rem)' }">
            <!-- 修改字体大小 -->
            <div class="fontsize">
              <span class="title">字号</span>
              <div class="box">
                <div class="de" :style="{ opacity: $store.state.fontSize == 12 ? 0.5 : 1 }" @click="changeFontSize('de')">A-</div>
                <span class="f">{{ $store.state.fontSize }}</span>
                <div class="in" :style="{ opacity: $store.state.fontSize == 28 ? 0.5 : 1 }" @click="changeFontSize('in')">A+</div>
                <div class="fam" @click="$router.push('/fontfam')">
                  <span>系统字体</span>
                  <img :src="enterIcon" />
                </div>
              </div>
            </div>
            <!-- 修改主题 -->
            <div class="theme">
              <span class="title">背景</span>
              <div class="box">
                <div
                  class="white"
                  :style="{ border: $store.state.theme == 'white' ? '1px solid black' : 'none' }"
                  @click="changeTheme('white')"
                ></div>
                <div
                  class="yellow"
                  :style="{ border: $store.state.theme == 'yellow' ? '1px solid black' : 'none' }"
                  @click="changeTheme('yellow')"
                ></div>
                <div
                  class="green"
                  :style="{ border: $store.state.theme == 'green' ? '1px solid black' : 'none' }"
                  @click="changeTheme('green')"
                ></div>
                <div class="blue" :style="{ border: $store.state.theme == 'blue' ? '1px solid black' : 'none' }" @click="changeTheme('blue')"></div>
                <div class="dark" :style="{ border: $store.state.theme == 'dark' ? '1px solid #8a8a8a' : 'none' }" @click="changeTheme('dark')">
                  <img :src="moonIcon" />
                </div>
                <div class="more" @click="$router.push('/moreTheme')">
                  <span>更多</span>
                  <img :src="enterIcon" />
                </div>
              </div>
            </div>
            <!-- 翻页模式 -->
            <div class="mode">
              <span class="title">翻页</span>
              <div class="box">
                <div
                  class="real"
                  :style="{
                    border:
                      $store.state.mode == 'real'
                        ? $store.state.theme == 'dark'
                          ? '1px solid #8a8a8a'
                          : '1px solid black'
                        : '0.6px solid var(--thin-line-color)',
                  }"
                  @click="changeMode('real')"
                >
                  仿真
                </div>
                <div
                  class="cover"
                  :style="{
                    border:
                      $store.state.mode == 'cover'
                        ? $store.state.theme == 'dark'
                          ? '1px solid #8a8a8a'
                          : '1px solid black'
                        : '0.6px solid var(--thin-line-color)',
                  }"
                  @click="changeMode('cover')"
                >
                  覆盖
                </div>
                <div
                  class="trans"
                  :style="{
                    border:
                      $store.state.mode == 'trans'
                        ? $store.state.theme == 'dark'
                          ? '1px solid #8a8a8a'
                          : '1px solid black'
                        : '0.6px solid var(--thin-line-color)',
                  }"
                  @click="changeMode('trans')"
                >
                  平移
                </div>
                <div
                  class="scrol"
                  :style="{
                    border:
                      $store.state.mode == 'scroll'
                        ? $store.state.theme == 'dark'
                          ? '1px solid #8a8a8a'
                          : '1px solid black'
                        : '0.6px solid var(--thin-line-color)',
                  }"
                  @click="changeMode('scroll')"
                >
                  滚动
                </div>
              </div>
            </div>
            <div class="line"></div>
            <!-- 自动阅读和更多设置 -->
            <div class="more">
              <div class="auto" @click.stop="readAuto = !readAuto">{{ readAuto ? '关闭自动阅读' : '开启自动阅读' }}</div>
              <div class="li"></div>
              <div class="set" @click="$router.push('/moreSet')">更多设置</div>
            </div>
            <div class="line"></div>
          </div>
          <!-- 四大选项 -->
          <div class="tabs">
            <div class="item" @click="popShow = !popShow">
              <img :src="catalogIcon" />
              <span>目录</span>
            </div>
            <div class="item" @click="darkClick">
              <img :src="darkIcon" />
              <span :style="{ color: $store.state.theme == 'dark' ? '#F2693F' : 'inherit' }">夜间</span>
            </div>
            <div class="item" @click="brightClick">
              <img :src="brightIcon" />
              <span :style="{ color: showBright ? '#F2693F' : 'inherit' }">亮度</span>
            </div>
            <div class="item" @click="settingClick">
              <img :src="settingIcon" />
              <span :style="{ color: showSetting ? '#F2693F' : 'inherit' }">设置</span>
            </div>
          </div>
        </div>
        <!-- 书本首页 -->
        <div class="index" v-show="!chapterIndex && !loading">
          <!-- 开始阅读按钮 -->
          <k-button
            class="start"
            :bgColor="$store.state.theme == 'dark' ? 'var(--warning)' : 'var(--success)'"
            fontSize="0.16rem"
            fontColor="white"
            @click="chapterIndex = 1"
          >
            免费阅读
          </k-button>
          <!-- 小说信息详情 -->
          <div class="novel-info">
            <img class="cover" :src="novel.img" />
            <div class="name">{{ novel.name }}</div>
            <div class="more">
              <span class="author">{{ novel.author }}</span>
              <div class="line"></div>
              <span class="status">{{ novel.status }}</span>
              <span class="spot">·</span>
              <span class="words">{{ (novel.wordnumber / 10000).toFixed(1) }}万字</span>
            </div>
          </div>
          <div class="line"></div>
          <!-- 小说数据信息 -->
          <div class="novel-data">
            <div class="a">
              <div class="rate">
                <span class="grade">{{ novel.rate.toFixed(1) }}</span>
                <span class="fen">分</span>
              </div>
              <span class="clicktimes">{{ (novel.clicktimes / 10000).toFixed(1) }}万人点击</span>
            </div>
            <div class="b">
              <div class="readpeople">
                <span class="num">{{ (novel.readpeople / 10000).toFixed(1) }}</span>
                <span class="people">万人</span>
              </div>
              <span class="onread">正在阅读</span>
            </div>
            <div class="c">
              <div class="updatetime">
                <span class="time">{{ novel.updatetime | format }}</span>
              </div>
              <span class="t">更新时间</span>
            </div>
          </div>
          <!-- 简介 -->
          <div class="introduce">
            <div class="title">
              <span class="t">简介</span>
              <div class="tags">
                <span v-for="item in JSON.parse(novel.tags)" :key="item">{{ item }}</span>
              </div>
            </div>
            <div class="context" @click="showIntroduce">{{ novel.introduce }}</div>
          </div>
          <!-- 书评 -->
          <div class="review">
            <div class="title">热门书评</div>
            <div class="context">
              <!-- 随机用户头像 -->
              <img :src="avatar" />
              <div class="a">
                <span>{{ novel.evaluate }}</span>
                <div class="b">
                  <van-rate v-model="value" disabled />
                  <span>阅读{{ readtime }}小时点评</span>
                </div>
              </div>
            </div>
          </div>
          <!-- 责任提示 -->
          <div class="tip">
            <div class="a">本书转自于网络</div>
            <div class="b">如有版权问题请联系我们进行删除</div>
          </div>
        </div>
        <!-- 加载中 -->
        <div v-if="loading" class="loading">
          <van-loading size="24px">加载中...</van-loading>
        </div>
        <!-- 章节内容 -->
        <div class="chapter" v-show="chapterIndex && !loading" id="chapter">
          <div class="title" :style="{ fontSize: ($store.state.fontSize + 3) / 100 + 'rem' }">
            <span v-if="chapterContext.title">{{ chapterContext.title.replace(/章/, '章 ') }}</span>
          </div>
          <div class="context" :style="{ fontSize: $store.state.fontSize / 100 + 'rem', lineHeight: ($store.state.fontSize * 2) / 100 + 'rem' }">
            <div
              class="item-part"
              :style="{ marginTop: $store.state.lineHeight / 100 + 'rem', 'letter-spacing': $store.state.fontSize * 0.063 + 'px' }"
              v-for="(item, index) in chapterContext.context"
              :key="JSON.stringify(item) + index"
            >
              {{ item }}
            </div>
          </div>
          <div v-if="catalog.length - 1 != chapterIndex" class="navigation">
            <k-button @click="chapterIndex--" class="btn1" bgColor="primary" fontSize="0.14rem" fontColor="white">上一章</k-button>
            <k-button @click="chapterIndex++" class="btn2" bgColor="primary" fontSize="0.14rem" fontColor="white">下一章</k-button>
          </div>
          <div v-if="catalog.length - 1 == chapterIndex" class="over">
            <div v-if="novel.status == '连载中'" class="">等待作者更新...</div>
            <div v-if="novel.status == '完结'" class="">--- 本小说已完结 ---</div>
          </div>
        </div>
      </div>
    </k-scroll>
  </div>
</template>

<script>
import { catalogue } from './const' //引入popup参数配置

// import slider from '@/components/k-slider/slider.vue' //引入滑块组件
export default {
  name: 'read',
  data() {
    return {
      //返回图标
      catalogue, //目录popup
      popShow: false, //是否显示对话框
      showMenu: false, //是否显示顶部和底部操作菜单
      showBright: false, //是否显示亮度调节
      showSetting: false, //是否显示设置
      careEye: false, //是否开启护眼模式
      showChapterTip: false, //是否显示章节提示
      readAuto: false, //是否开启自动阅读
      showAutoSet: false, //是否显示自动阅读设置
      brightness: 15, //亮度百分比
      novel: {
        img: '', //小说封面地址
        name: '', //小说名字
        author: '', //小说作者
        status: '', //小说状态
        wordnumber: 0, //小说总字数
        rate: 0, //小说评分
        clicktimes: 0, //小说点击次数
        readpeople: 0, //小说阅读人数
        updatetime: 0, //小说最后更新时间戳
        tags: '[]', //小说的标签
        type: '', //小说的类型
        introduce: '', //小说简介
        evaluate: '', //小说的热门书评
        website: '', //小说来源网站
        noveltable: '', //小说表名
      },
      avatar: require('@/assets/img/other/kk.jpg'), //随机用户头像地址
      readtime: Math.round(Math.random() * 10) + 1, //随机小说阅读小时
      value: Math.round(Math.random() * 4) + 1, //星星数量

      chapterContext: {}, //当前小说的章节数据
      sort: '倒序', //章节顺序
      catalog: [], //小说目录章节数组
      chapterIndex: 0, //当前所在章节索引
      slider: 0, //滑块位置
      readSeconds: 0, //当前阅读秒数
      readProgress: 0.0, //当前阅读进度
      timeStamp: new Date().getTime(), //当前时间戳
      electri: 1, //当前手机电量
      id: 0, //定时器id
      loading: false, //是否正在加载章节内容
      scrollY: 0, //当前滚动位置
      id_auto: 0, //自动阅读定时器id
      chapterHeight: 0, //章节内容的高度
      pageHeight: 0, //网页的高度
      readSpeed: 20, //默认20,最快5,最慢35
    }
  },
  //计算属性
  computed: {
    //返回图标
    backIcon() {
      return this.$store.state.theme == 'dark' ? require('@/assets/img/icons/light/back.svg') : require('@/assets/img/icons/dark/back.svg')
    },
    //下载图标
    downloadIcon() {
      return this.$store.state.theme == 'dark' ? require('@/assets/img/icons/light/download.svg') : require('@/assets/img/icons/dark/download.svg')
    },
    //更多图标
    moreIcon() {
      return this.$store.state.theme == 'dark' ? require('@/assets/img/icons/light/more.svg') : require('@/assets/img/icons/dark/more.svg')
    },
    //目录图标
    catalogIcon() {
      return this.$store.state.theme == 'dark' ? require('@/assets/img/icons/light/catalog.svg') : require('@/assets/img/icons/dark/catalog.svg')
    },
    //亮度图标
    brightIcon() {
      if (this.showBright) return require('@/assets/img/icons/selected/bright.svg')
      return this.$store.state.theme == 'dark' ? require('@/assets/img/icons/light/bright.svg') : require('@/assets/img/icons/dark/bright.svg')
    },
    //亮度图标
    brightIcon2() {
      return this.$store.state.theme == 'dark' ? require('@/assets/img/icons/light/bright.svg') : require('@/assets/img/icons/dark/bright.svg')
    },
    //夜间图标
    darkIcon() {
      return this.$store.state.theme == 'dark' ? require('@/assets/img/icons/selected/dark.svg') : require('@/assets/img/icons/dark/dark.svg')
    },
    //设置图标
    settingIcon() {
      if (this.showSetting) return require('@/assets/img/icons/selected/setting.svg')
      return this.$store.state.theme == 'dark' ? require('@/assets/img/icons/light/setting.svg') : require('@/assets/img/icons/dark/setting.svg')
    },
    //进入图标
    enterIcon() {
      return this.$store.state.theme == 'dark' ? require('@/assets/img/icons/light/enter.svg') : require('@/assets/img/icons/dark/enter.svg')
    },
    //月亮图标
    moonIcon() {
      return this.$store.state.theme == 'dark' ? require('@/assets/img/icons/light/moon.svg') : require('@/assets/img/icons/dark/moon.svg')
    },
    //向上图标
    upIcon() {
      return this.$store.state.theme == 'dark' ? require('@/assets/img/icons/light/up.svg') : require('@/assets/img/icons/dark/up.svg')
    },
  },
  //观察变量
  watch: {
    //控制目录滚动指定位置
    popShow(value) {
      if (value) {
        this.showMenu = false //关闭菜单
        setTimeout(() => {
          let listHeight = document.getElementById('scroll2').clientHeight
          let titleItemHeight = document.getElementById('titleItem').clientHeight + 0.7
          if (this.sort == '倒序') {
            if ((this.chapterIndex + 2) * titleItemHeight > listHeight / 2) {
              console.log('滚动')
              document.getElementById('scroll2').scrollTop = (this.chapterIndex + 2) * titleItemHeight - listHeight / 2
            }
          }
          if (this.sort == '正序') {
            console.log(this.catalog.length - this.chapterIndex)
            if ((this.catalog.length - this.chapterIndex + 2) * titleItemHeight > listHeight / 2) {
              console.log('滚动')
              document.getElementById('scroll2').scrollTop = (this.catalog.length - this.chapterIndex + 2) * titleItemHeight - listHeight / 2
            }
          }
        }, 100)
      }
    },
    //观察章节索引的变化来获取指定章节的内容
    chapterIndex(value) {
      if (value) {
        this.scrollY = 0 //重置滚动位置
        this.getNovelChapter(value) // 获取章节的内容
        this.slider = value //滑块同步
      } else {
        this.readAuto = false //关闭自动阅读
      }
    },
    //观察是否显示菜单
    showMenu(value) {
      if (!value) {
        this.showBright = false //关闭亮度
        this.showSetting = false //关闭设置
      }
    },
    //重置定时器
    readSpeed() {
      clearInterval(this.id_auto) //清除定时器
      this.id_auto = setInterval(() => {
        //本章节阅读自动完毕
        if (!this.chapterHeight) return //暂无内容高度
        //内容过短直接跳过
        if (this.chapterHeight - this.pageHeight - 20 <= 0) {
          this.chapterHeight = 1600
          this.chapterIndex++ //下一章
        }
        if (this.scrollY >= this.chapterHeight - this.pageHeight - 20) {
          if (this.chapterIndex == this.catalog.length - 1) {
            this.$toast({
              message: '本小说已阅读完毕！',
            })
            clearInterval(this.id_auto) //清除定时器
            return
          }
          this.chapterIndex++ //下一章
        }
        this.$refs.scroll.scrollTo(this.scrollY + 1)
      }, 40 - this.readSpeed)
    },
    //观察是否开启自动阅读
    readAuto(value) {
      if (value) {
        this.showMenu = false //关闭菜单
        this.showBright = false //关闭亮度
        this.showSetting = false //关闭设置
        if (!this.chapterIndex) {
          this.chapterIndex++ //下一章
        }
        this.id_auto = setInterval(() => {
          //本章节阅读自动完毕
          if (!this.chapterHeight) return //暂无内容高度
          //内容过短直接跳过
          if (this.chapterHeight - this.pageHeight - 20 <= 0) {
            this.chapterHeight = 1600
            this.chapterIndex++ //下一章
          }
          if (this.scrollY >= this.chapterHeight - this.pageHeight - 20) {
            if (this.chapterIndex == this.catalog.length - 1) {
              this.$toast({
                message: '本小说已阅读完毕！',
              })
              this.readAuto = false //停止自动阅读
              return
            }
            this.chapterIndex++ //下一章
          }
          this.$refs.scroll.scrollTo(this.scrollY + 1)
        }, 40 - this.readSpeed)
      } else {
        this.showAutoSet = false //收起自动阅读设置
        this.$toast({
          message: '已退出自动阅读',
        })
        clearInterval(this.id_auto) //清除定时器
      }
    },
  },
  //组件挂载完成
  mounted() {
    this.pageHeight = this.$refs.page.clientHeight //获取网页高度
    this.getNovelInfo() //获取小说基本信息
    this.getNovelCatalog() //获取小说目录全部章节
    //定时器
    this.id = setInterval(() => {
      this.timeStamp = new Date().getTime() //更新当前时间戳
      this.readSeconds += 1 //增加阅读秒数
      //获取手机状态信息
      navigator.getBattery().then((battery) => {
        this.electri = battery.level //赋值手机电量
      })
      if (this.readSeconds == 300) {
        this.readSeconds = 0 //归零
        this.submitReadTime()
      }
    }, 1000)
  },
  //过滤器
  filters: {
    //时间戳格式化
    format(s) {
      let ds = Math.floor((new Date().getTime() - s) / 1000)
      if (ds >= 365 * 24 * 60 * 60) {
        return Math.floor(ds / (365 * 24 * 60 * 60)) + '年前'
      } else if (ds >= 30 * 24 * 60 * 60) {
        return Math.floor(ds / (30 * 24 * 60 * 60)) + '月前'
      } else if (ds >= 1 * 24 * 60 * 60) {
        return Math.floor(ds / (1 * 24 * 60 * 60)) + '天前'
      } else if (ds >= 1 * 60 * 60) {
        return Math.floor(ds / (1 * 60 * 60)) + '小时前'
      } else if (ds >= 1 * 60) {
        return Math.floor(ds / (1 * 60)) + '分钟前'
      } else {
        return ds + '秒前'
      }
    },
    //格式化显示当前时间
    format_nowtime(t) {
      let h = new Date(t).getHours()
      h = h > 9 ? h : '0' + h
      let m = new Date(t).getMinutes()
      m = m > 9 ? m : '0' + m
      return h + ':' + m
    },
  },
  //路由离开前销毁定时器
  beforeRouteLeave(to, from, next) {
    clearInterval(this.id)
    clearInterval(this.id_auto)
    next()
  },
  methods: {
    //书本换源
    selectOrigin() {
      this.$router.push({
        path: '/selectOrigin',
        query: {
          name: this.$route.query.name,
          author: this.$route.query.author,
        },
      })
    },
    //加入书架
    joinRack() {
      //书架key(bookrack)
      if (localStorage.getItem('bookrack')) {
        let obj = {}
        obj.name = this.novel.name //书名
        obj.author = this.novel.author //作者名
        obj.img = this.novel.img //书封面
        obj.url = this.novel.url //首页网址
        obj.origin = this.novel.origin //来源网站
        obj.status = this.novel.status //小说状态
      } else {
      }
    },
    //下载本书到本地
    downLoad() {
      //下载到indexDB本地数据库
      this.$router.push({
        path: '/downloadBook',
        query: {
          name: this.$route.query.name,
          author: this.$route.query.author,
        },
      })
    },
    //更多被点击
    moreClick() {},
    //页面被点击
    pageClick() {
      if (this.loading) return
      //正在显示自动阅读设置
      if (this.showAutoSet) {
        this.showAutoSet = false //关闭自动阅读设置
      } else {
        this.showMenu = !this.showMenu //取反
        if (!this.showMenu) {
          this.showBright = false //关闭亮度
          this.showSetting = false //关闭设置
        }
      }
    },
    //修改字体大小
    changeFontSize(value) {
      //字体加大
      if (value == 'in') {
        if (this.$store.state.fontSize == 28) return
        this.$store.commit('changeFontSize', this.$store.state.fontSize + 1)
        setTimeout(() => {
          this.chapterHeight = document.getElementById('chapter').clientHeight //设置章节内容高度
        }, 50)
      }
      //字体减小
      if (value == 'de') {
        if (this.$store.state.fontSize == 12) return
        this.$store.commit('changeFontSize', this.$store.state.fontSize - 1)
        setTimeout(() => {
          this.chapterHeight = document.getElementById('chapter').clientHeight //设置章节内容高度
        }, 50)
      }
    },
    //修改阅读背景
    changeTheme(theme) {
      this.$store.commit('changeTheme', theme)
    },
    //修改翻页模式
    changeMode(mode) {
      this.$store.commit('changeMode', mode)
    },
    //滚动事件
    scroll(e) {
      this.scrollY = e
    },
    //修改夜间
    darkClick() {
      if (this.$store.state.theme == 'dark') {
        this.$store.commit('changeTheme', 'yellow')
      } else {
        this.$store.commit('changeTheme', 'dark')
      }
    },
    //亮度被点击
    brightClick() {
      this.showBright = !this.showBright //取反
      if (this.showBright) {
        this.showSetting = false
      }
    },
    //设置被点击
    settingClick() {
      this.showSetting = !this.showSetting //取反
      if (this.showSetting) {
        this.showBright = false
      }
    },
    //滑块改变事件
    sliderChange(e) {
      this.chapterIndex = e
    },
    //上章节
    before() {
      if (!this.chapterIndex) return
      this.chapterIndex--
    },
    //下一章
    next() {
      if (this.chapterIndex == this.catalog.length - 1) return
      this.chapterIndex++
    },
    //改变章节排序
    changeSort() {
      if (this.sort == '倒序') {
        this.sort = '正序'
        this.catalog.reverse()
      } else {
        this.sort = '倒序'
        this.catalog.reverse()
      }
    },
    //展示小说简介
    showIntroduce() {
      return
      this.$dialog({
        title: '小说简介',
        message: this.novel.introduce,
      })
    },
    //修改当前章节
    changeChapter(index) {
      if (this.sort == '倒序') this.chapterIndex = index
      if (this.sort == '正序') this.chapterIndex = this.catalog.length - index - 1
      console.log(this.chapterIndex)
      this.popShow = false //关闭目录
    },
    //获取小说目录全部章节标题
    getNovelCatalog() {
      this.$network
        .main('getNovelCatalog', this.$route.query.table)
        .then((data) => {
          this.catalog = data //赋值小说目录全部章节
          this.catalog.splice(0, 0, { title: '书封页' })
        })
        .catch((err) => {
          this.$dialog({
            title: '获取小说章节失败',
            message: 'msg：' + err,
          })
        })
    },
    //获取小说的详细信息
    getNovelInfo() {
      this.loading = true
      this.$network
        .main('getNovelInfo', this.$route.query.table)
        .then((data) => {
          this.loading = false
          this.novel = data //赋值
        })
        .catch((err) => {
          this.$dialog({
            title: 'Error',
            message: 'msg：' + err,
          })
        })
    },
    //获取小说的的章节内容
    getNovelChapter(index) {
      this.loading = true //显示加载中
      this.$network
        .main('getNovelChapter', this.novel.noveltable, index - 1)
        .then((data) => {
          this.chapterContext.title = data.title //标题
          this.chapterContext.context = [] //内容
          for (let item of data.context.split('ζ')) {
            this.chapterContext.context.push('\u2003\u2003' + item.replace(/\s|[\r\n]|<br>|<div>|<\/div>|/g, ''))
          }
          this.chapterContext.context = this.chapterContext.context.filter((item) => item) //清除掉空段落
          // console.log(this.chapterContext)
          setTimeout(() => {
            this.loading = false //关闭加载中
            if (!this.loading) {
              setTimeout(() => {
                this.chapterHeight = document.getElementById('chapter').clientHeight //设置章节内容高度
              }, 50)
            }
          }, 100)
        })
        .catch((err) => {
          this.loading = false //关闭加载中
          this.$dialog({
            title: '获取章节内容失败',
            message: 'msg：' + err,
          })
        })
    },
    //提交阅读时间和奖励
    submitReadTime() {
      if (this.$store.state.token) {
        //提交阅读时间记录和阅读奖励
        this.$network
          .main('submitReadTime', 5)
          .then((data) => {
            this.$toast({
              type: 'text',
              position: 'middle',
              message: '获得5金币阅读奖励！',
            })
          })
          .catch((err) => {
            this.$dialog({
              title: '提交阅读时间失败',
              message: 'msg：' + err,
            })
          })
      }
    },
  },
}
</script>

<style lang="less" scoped src="./index.less"></style>
